/*
** remote_write.c for pud in mrcellophane/libpud
** 
** Made by solomon hykes
** Login   <torgau@gmail.com>
** 
** Started on  Mon May 16 23:49:58 2005 solomon hykes
** Last update Tue May 17 12:13:34 2005 solomon hykes
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

#include "pud.h"

static  pud_process	*proc = NULL;

void	bye(int sig)
{
  if (proc != NULL)
    pud_detach(proc);
  exit(0);
}

int	main(int argc, char **argv)
{
  int	pid;
  u_long	addr;
  long		len;
  long		ret;
  char		*buf;

  if (argc < 4)
    {
      fprintf(stderr, "Usage: %s pid addr length\n\nRead <length> bytes from process <pid> at address <addr>\n", argv[0]);
      exit(1);
    }
  pid = atoi(argv[1]);
  addr = (u_long)strtoul(argv[2], (char **)NULL, 16);
  len = atoi(argv[3]);
  fprintf(stderr, "pid=%d, addr=%p, len=%d\n", pid, addr, len);
  buf = malloc(len);
  ret = read(0, buf, len);
  signal(SIGINT, &bye);
  pswrite(pid, addr, buf, ret);
}



int	pswrite(int pid, u_long addr, void *data, int len)
{

  pud_event	*event;
  int		ret;

  proc = pud_attach(pid);
  if (proc == NULL)
    {
      perror("pud_attach");
      exit(1);
    }
  event = pud_next_event(proc);
  if (event == NULL)
    {
      perror("pud_next_event");
      pud_detach(proc);
      exit(1);
    }
  ret = pud_mem_write(proc, addr, data, len);
  if (ret == -1)
    {
      perror("pud_mem_write()");
      pud_detach(proc);
      exit(1);
    }
  pud_detach(proc);
  return (ret);
}
